package com.furnitur.modules.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.furnitur.common.utils.SecurityUtils;
import com.furnitur.core.entity.address.Address;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.mapper.address.AddressMapper;
import com.furnitur.modules.portal.dto.address.AddressDTO;
import com.furnitur.modules.portal.service.PortalAddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class PortalAddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements PortalAddressService {

    @Override
    @Transactional
    public Address addAddress(AddressDTO addressDTO) {
        Address address = new Address();
        BeanUtils.copyProperties(addressDTO, address);
        
        User currentUser = SecurityUtils.getCurrentUser();
        address.setUserId(currentUser.getId());
        
        Date now = new Date();
        address.setCreatedAt(now);
        address.setUpdatedAt(now);
        
        // 如果是第一个地址或指定为默认地址
        if (count(new QueryWrapper<Address>().eq("user_id", currentUser.getId())) == 0
            || Boolean.TRUE.equals(addressDTO.getIsDefault())) {
            // 清除其他默认地址
            Address updateEntity = new Address();
            updateEntity.setIsDefault(false);
            update(updateEntity,
                  new QueryWrapper<Address>().eq("user_id", currentUser.getId()));
            address.setIsDefault(true);
        }
        
        save(address);
        return address;
    }

    @Override
    @Transactional
    public Address updateAddress(Long id, AddressDTO addressDTO) {
        Address address = validateAddressOwnership(id);
        BeanUtils.copyProperties(addressDTO, address);
        address.setUpdatedAt(new Date());

        // 如果设为默认地址，清除其他默认地址
        if (Boolean.TRUE.equals(addressDTO.getIsDefault())) {
            Address updateEntity = new Address();
            updateEntity.setIsDefault(false);
            update(updateEntity,
                  new QueryWrapper<Address>()
                      .eq("user_id", address.getUserId())
                      .ne("id", id));
        }

        updateById(address);
        return address;
    }

    @Override
    @Transactional
    public void deleteAddress(Long id) {
        Address address = validateAddressOwnership(id);
        removeById(id);

        // 如果删除的是默认地址，设置最新的地址为默认地址
        if (Boolean.TRUE.equals(address.getIsDefault())) {
            Address newDefault = getOne(new QueryWrapper<Address>()
                    .eq("user_id", address.getUserId())
                    .orderByDesc("created_at")
                    .last("LIMIT 1"));
            if (newDefault != null) {
                newDefault.setIsDefault(true);
                updateById(newDefault);
            }
        }
    }

    @Override
    public List<Address> getAddressList() {
        User currentUser = SecurityUtils.getCurrentUser();
        return list(new QueryWrapper<Address>()
                .eq("user_id", currentUser.getId())
                .orderByDesc("is_default")
                .orderByDesc("created_at"));
    }

    @Override
    public Address getDefaultAddress() {
        User currentUser = SecurityUtils.getCurrentUser();
        return getOne(new QueryWrapper<Address>()
                .eq("user_id", currentUser.getId())
                .eq("is_default", true));
    }

    @Override
    @Transactional
    public void setDefaultAddress(Long id) {
        Address address = validateAddressOwnership(id);
        // 清除其他默认地址
        Address updateEntity = new Address();
        updateEntity.setIsDefault(false);
        update(updateEntity,
              new QueryWrapper<Address>()
                  .eq("user_id", address.getUserId())
                  .ne("id", id));
        // 设置新的默认地址
        address.setIsDefault(true);
        updateById(address);
    }

    private Address validateAddressOwnership(Long id) {
        User currentUser = SecurityUtils.getCurrentUser();
        Address address = getById(id);
        if (address == null || !address.getUserId().equals(currentUser.getId())) {
            throw new RuntimeException("地址不存在或无权限");
        }
        return address;
    }
} 